package com.fc.happyteam.controller.api;


import com.fc.happyteam.controller.BaseController;
import com.fc.happyteam.dtos.ResponseJson;
import com.fc.happyteam.dtos.UserRegRequest;
import com.fc.happyteam.entity.MenuEntity;
import com.fc.happyteam.entity.SmsHistoryEntity;
import com.fc.happyteam.entity.UserEntity;
import com.fc.happyteam.exception.ResponseException;
import com.fc.happyteam.service.*;
import com.fc.happyteam.utils.SessionUtils;
import com.fc.happyteam.utils.annotation.IgnoreAuth;
import com.fc.happyteam.utils.annotation.SysLog;
import com.fc.happyteam.validate.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/api/user")
@Api(value="用户相关的API", tags={"用户接口"})
public class UserController extends BaseController {
	private final IUserService userService;

	private final IUserRoleService roleService;

	private final IUserPermService userPermService;

	private final ISmsHistoryService smsHistoryService;

	private final IMenuService menuService;

    @Autowired
    public UserController(IUserService userService, IUserRoleService roleService, IUserPermService userPermService, ISmsHistoryService smsHistoryService, IMenuService menuService) {
        this.userService = userService;
        this.roleService = roleService;
        this.userPermService = userPermService;
        this.smsHistoryService = smsHistoryService;
        this.menuService = menuService;
    }

	@ApiOperation(value = "获取当前登录用户的信息",
			notes = "获取当前登录用户的信息",
			response = ResponseJson.class,
			httpMethod = "GET",
			consumes = "application/json",
			produces = "application/json"
	)
	@GetMapping("/info")
	public ResponseJson info(){
		ResponseJson responseJson = new ResponseJson();
		Long currentUserId = getUserId();
		if(currentUserId == null)
		{
			throw new ResponseException("无法获取到用户信息！");
		}
		return responseJson.success(userService.queryObject(currentUserId));
	}
	/**
	 * 注册
	 */
	@IgnoreAuth
	@PostMapping("register")
	@ApiOperation(value = "注册")
	public ResponseJson registerUser(@RequestBody UserRegRequest reg){
		ResponseJson responseJson = new ResponseJson();
		Assert.isBlank(reg.getPhone(), "手机号不能为空");
		Assert.isBlank(reg.getPassword(), "密码不能为空");

		if(userService.queryByMobile(reg.getPhone()) != null){
			responseJson.setSuccess(false);
			responseJson.setMsg("该手机号已注册");
			return responseJson;
		}

		if(reg.getInviteCode()!=null && "888888".equals(reg.getInviteCode())){// For debug register only
			userService.save(reg.getPhone(), reg.getPassword());
			responseJson.setSuccess(true);
			responseJson.setMsg("");
			return responseJson;
		}else{
			SmsHistoryEntity smsHistoryEntity = smsHistoryService.queryByMobileAndCode(reg.getPhone(), reg.getVerifyCode());
			if (null == smsHistoryEntity)
			{
				return ResponseJson.error(200, "验证码不正确");
			}
			userService.save(reg.getPhone(), reg.getPassword());
			responseJson.setSuccess(true);
			responseJson.setMsg("");
			return responseJson;
		}




	}

	@ApiOperation(value = "修改当前登录用户密码",
			notes = "修改当前登录用户密码",
			response = ResponseJson.class,
			httpMethod = "POST",
			consumes = "application/json",
			produces = "application/json"
	)
	@SysLog("修改密码")
	@RequestMapping("/password")
	public ResponseJson password(
			@ApiParam(name="password", required=true) String password,
			@ApiParam(name="newPassword", required=true) String newPassword){
		Assert.isBlank(newPassword, "新密码不为能空");
		
		//sha256加密
		password = new Sha256Hash(password).toHex();
		//sha256加密
		newPassword = new Sha256Hash(newPassword).toHex();
				
		//更新密码
		int count = userService.updatePassword(getUserId(), password, newPassword);
		if(count == 0){
			return ResponseJson.error("原密码不正确");
		}
		
		//退出
		SessionUtils.logout();
		
		return ResponseJson.success();
	}

	@ApiOperation(value = "获取指定用户的信息",
			notes = "获取指定用户的信息",
			response = ResponseJson.class,
			httpMethod = "GET",
			consumes = "application/json",
			produces = "application/json"
	)
	@RequestMapping("/info/{userId}")
	@RequiresPermissions("api:user:info")
	public ResponseJson info(@PathParam("userId") @PathVariable("userId") Long userId){
		UserEntity user = userService.queryObject(userId);
		return ResponseJson.success(user);
	}

	@ApiOperation(value = "获取指定用户的权限",
			notes = "获取指定用户的权限",
			response = ResponseJson.class,
			httpMethod = "GET",
			consumes = "application/json",
			produces = "application/json"
	)
	@RequestMapping("/perms/{userId}")
	@RequiresPermissions("api:user:perms:view")
	public ResponseJson perms(@PathParam("userId") @PathVariable("userId") Long userId){
		Set<String> perms = userPermService.queryPermissionSet(userId);
		return ResponseJson.success(perms);
	}

	@ApiOperation(value = "获取指定用户的菜单",
			notes = "获取指定用户的菜单",
			response = ResponseJson.class,
			httpMethod = "GET",
			consumes = "application/json",
			produces = "application/json"
	)
	@GetMapping("/menu/{userId}")
	@RequiresPermissions("api:user:menu:view")
	public ResponseJson menus(@PathParam("userId") @PathVariable("userId") Long userId){
		if(userService.queryObject(userId)== null ){
			return ResponseJson.error("用户不存在");
		}
		List<MenuEntity> menus = menuService.queryByUserIds(userId);
		return ResponseJson.success(menus);
	}
}
